<template>
    <div class="Box">
      <!-- 顶部搜索 -->
      <div class="SearchBox flex-LAR">
        <el-input v-model="SearchKeyWord.searchValue" placeholder="请输入搜索内容" class="input-with-select">
          <template #prepend>
            <el-select v-model="SearchKeyWord.selectKey" style="width: 6.25rem">
              <el-option label="团队名称" value="team_name" />
              <el-option label="负责人" value="leader_name" />
            </el-select>
          </template>
          <template #append>
            <el-button class="searchBtn" :icon="Search" />
          </template>
        </el-input>
        <div>
          <el-button type="success" @click="handleAdd">新增团队</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <div class="TableBox">
        <cy-table class="Table" row-key="team_id" :data="tableData" :columns="ruleTable.columns" :loading="loading" />
      </div>
      <!-- 分页 -->
      <div class="PageBox">
        <el-pagination :hide-on-single-page="true" v-model:current-page="page.currentPage" v-model:page-size="page.pageSize"
          v-model:total="page.total" />
      </div>
  
      <!-- 新增/编辑弹窗 -->
      <el-dialog v-model="dialogVisible" :title="dialogTitle" width="70%">
        <el-form :model="form" label-width="120px" :rules="rules" ref="formRef">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="团队名称" prop="team_name">
                <el-input v-model="form.team_name" placeholder="请输入团队名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="团队类型" prop="team_type">
                <el-select v-model="form.team_type" placeholder="请选择团队类型">
                  <el-option v-for="item in teamTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="负责人" prop="leader_id">
                <el-select v-model="form.leader_id" placeholder="请选择负责人">
                  <el-option v-for="person in personnelList" :key="person.personnel_id" :label="person.name"
                    :value="person.personnel_id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="成立日期" prop="establishment_date">
                <el-date-picker v-model="form.establishment_date" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" />
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-form-item label="团队职责" prop="responsibilities">
            <el-input v-model="form.responsibilities" type="textarea" :rows="3" placeholder="请输入团队职责" />
          </el-form-item>
  
          <el-form-item label="团队成员" prop="members">
            <el-transfer 
              v-model="form.members" 
              :data="transferData" 
              :titles="['可选人员', '团队成员']"
              filterable
              filter-placeholder="请输入姓名搜索"
            />
          </el-form-item>
  
          <el-form-item label="团队描述" prop="description">
            <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入团队描述" />
          </el-form-item>
        </el-form>
  
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script lang="tsx" setup>
  import { ref, reactive, onMounted, computed } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Search } from "@element-plus/icons-vue";
  import CyTable from "@/components/table";
  
  const page = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
  });
  
  const SearchKeyWord = reactive({
    selectKey: "team_name",
    searchValue: "",
  });
  
  const tableData = ref([
    {
      team_id: 1,
      team_name: '应急救援一队',
      team_type: 'rescue',
      leader_id: 1,
      leader_name: '叶致远',
      establishment_date: '2020-05-10',
      responsibilities: '负责自然灾害、事故灾难等突发事件的现场救援工作',
      members: [1, 3, 5, 7],
      member_names: '叶致远, 金詩涵, 丁浩然, 崔秀英',
      description: '公司核心应急救援力量，24小时待命',
      status: 'active'
    },
    {
      team_id: 2,
      team_name: '医疗应急队',
      team_type: 'medical',
      leader_id: 2,
      leader_name: '向子韬',
      establishment_date: '2020-06-15',
      responsibilities: '负责公共卫生事件、医疗急救等应急处置',
      members: [2, 4, 6],
      member_names: '向子韬, 蒋嘉伦, 薛子轩',
      description: '专业医疗应急团队，具备现场急救能力',
      status: 'active'
    },
    {
      team_id: 3,
      team_name: '技术保障队',
      team_type: 'technical',
      leader_id: 4,
      leader_name: '蒋嘉伦',
      establishment_date: '2021-02-20',
      responsibilities: '负责网络安全、设备故障等技术类应急事件处理',
      members: [4, 8, 9],
      member_names: '蒋嘉伦, 卢晓明, 范冰冰',
      description: 'IT技术保障团队，提供技术支持',
      status: 'active'
    },
    {
      team_id: 4,
      team_name: '后勤保障队',
      team_type: 'logistics',
      leader_id: 6,
      leader_name: '薛子轩',
      establishment_date: '2021-08-12',
      responsibilities: '负责应急物资调配、后勤保障工作',
      members: [6, 10],
      member_names: '薛子轩, 彭于晏',
      description: '后勤保障支持团队',
      status: 'active'
    }
  ]);
  
  const ruleTable = reactive({
    columns: [
      { prop: "team_id", label: "团队ID" },
      { prop: "team_name", label: "团队名称" },
      {
        prop: "team_type", label: "团队类型",
        render: ({ row }) => (
          <el-tag type={getTeamTypeTag(row.team_type)}>
            {getTeamTypeName(row.team_type)}
          </el-tag>
        ),
      },
      { prop: "leader_name", label: "负责人" },
      { prop: "member_names", label: "团队成员" },
      { prop: "establishment_date", label: "成立日期" },
      {
        prop: "status", label: "状态",
        render: ({ row }) => (
          <el-tag type={getStatusTag(row.status)}>
            {getStatusName(row.status)}
          </el-tag>
        ),
      },
      {
        label: "操作",
        align: "center",
        width:250,
        render: ({ row }) => (
          <div>
            <el-button>查看</el-button>
            <el-button type="primary">编辑</el-button>
            <el-button type="danger">删除</el-button>
          </div>
        ),
      },
    ],
  });
  
  const personnelList = ref([
    { personnel_id: 1, name: '叶致远', department: '安全部' },
    { personnel_id: 2, name: '向子韬', department: '医疗部' },
    { personnel_id: 3, name: '金詩涵', department: '安全部' },
    { personnel_id: 4, name: '蒋嘉伦', department: 'IT部' },
    { personnel_id: 5, name: '丁浩然', department: '安全部' },
    { personnel_id: 6, name: '薛子轩', department: '后勤部' },
    { personnel_id: 7, name: '崔秀英', department: '安全部' },
    { personnel_id: 8, name: '卢晓明', department: 'IT部' },
    { personnel_id: 9, name: '范冰冰', department: 'IT部' },
    { personnel_id: 10, name: '彭于晏', department: '后勤部' },
  ]);
  
  const transferData = computed(() => {
    return personnelList.value.map(person => ({
      key: person.personnel_id,
      label: `${person.name} (${person.department})`
    }));
  });
  
  const dialogVisible = ref(false);
  const dialogTitle = ref('');
  const formRef = ref(null);
  
  const form = reactive({
    team_id: '',
    team_name: '',
    team_type: '',
    leader_id: '',
    establishment_date: '',
    responsibilities: '',
    members: [],
    description: '',
    status: 'active'
  });
  
  const rules = reactive({
    team_name: [{ required: true, message: '请输入团队名称', trigger: 'blur' }],
    team_type: [{ required: true, message: '请选择团队类型', trigger: 'change' }],
    leader_id: [{ required: true, message: '请选择负责人', trigger: 'change' }],
    establishment_date: [{ required: true, message: '请选择成立日期', trigger: 'change' }],
    responsibilities: [{ required: true, message: '请输入团队职责', trigger: 'blur' }],
  });
  
  const teamTypeOptions = ref([
    { value: 'rescue', label: '救援团队' },
    { value: 'medical', label: '医疗团队' },
    { value: 'technical', label: '技术团队' },
    { value: 'logistics', label: '后勤团队' },
    { value: 'other', label: '其他团队' }
  ]);
  
  const statusOptions = ref([
    { value: 'active', label: '活跃' },
    { value: 'inactive', label: '停用' },
    { value: 'training', label: '培训中' }
  ]);
  
  const getTeamTypeName = (type) => {
    const item = teamTypeOptions.value.find(item => item.value === type);
    return item ? item.label : '未知';
  };
  
  const getTeamTypeTag = (type) => {
    const map = {
      rescue: 'danger',
      medical: 'success',
      technical: 'info',
      logistics: 'warning',
      other: ''
    };
    return map[type] || '';
  };
  
  const getStatusName = (status) => {
    const item = statusOptions.value.find(item => item.value === status);
    return item ? item.label : '未知';
  };
  
  const getStatusTag = (status) => {
    const map = {
      active: 'success',
      inactive: 'danger',
      training: 'warning'
    };
    return map[status] || '';
  };
  
  const handleAdd = () => {
    dialogTitle.value = '新增应急团队';
    formRef.value?.resetFields();
    dialogVisible.value = true;
  };
  
  const submitForm = () => {
    formRef.value.validate((valid) => {
      if (valid) {
        if (form.team_id) {
          const index = tableData.value.findIndex(item => item.team_id === form.team_id);
          if (index !== -1) {
            tableData.value[index] = { 
              ...form,
              leader_name: getPersonnelName(form.leader_id),
              member_names: getMemberNames(form.members)
            };
            ElMessage.success('编辑成功');
          }
        } else {
          form.team_id = tableData.value.length + 1;
          tableData.value.push({ 
            ...form,
            leader_name: getPersonnelName(form.leader_id),
            member_names: getMemberNames(form.members),
            status: 'active'
          });
          ElMessage.success('新增成功');
        }
        dialogVisible.value = false;
      } else {
        ElMessage.error('表单验证失败');
      }
    });
  };
  
  const getPersonnelName = (id) => {
    const item = personnelList.value.find(item => item.personnel_id === id);
    return item ? item.name : '未知';
  };
  
  const getMemberNames = (ids) => {
    return ids.map(id => {
      const person = personnelList.value.find(person => person.personnel_id === id);
      return person ? person.name : '未知';
    }).join(', ');
  };
  </script>
  
  <style scoped lang="scss">
  .Box {
    position: relative;
  
    .SearchBox {
      width: 100%;
      height: 60px;
      background-color: #fff;
      border-bottom: 1px solid #eee;
  
      .el-input {
        width: 350px;
        margin-left: 0.5rem;
      }
  
      .searchBtn {
        color: rgb(15, 153, 245);
      }
  
      .addBtn {
        margin-right: 1rem;
      }
    }
  
    .PageBox {
      background-color: #fff;
      padding-left: 30%;
      margin: 1rem;
    }
  
    .TableBox {
      .Table {
        width: 100%;
        min-height: 25rem;
        border-top: 1px solid #eee;
      }
    }
  
    .EditForm {
      :deep(.el-form-item__content) {
        display: flex;
        justify-content: center;
        align-content: center;
      }
    }
  }
  
  :deep(.el-transfer-panel) {
    width: 300px;
  }
  
  :deep(.el-transfer__buttons) {
    padding: 0 16px;
  }
  </style>